import { Layout, UserSubPageBase, C13BottomDock, Icon } from "@/components";
import { useEffect, useState } from "react";
import { submitInvoice, useUserInfo } from "@/store/userDataContext";
import { Input, Picker, View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { ModalTypes, useApplicationInfo } from "@/store/applicationDataContext";
import { ApiInvoiceType } from "@/data/invoice/invoiceTypes";
import style from "./index.module.scss";

const INVOICE_TYPE_ARR = [ApiInvoiceType.Personal, ApiInvoiceType.Company];

type MandatoryFieldsContent = {
  value: string;
  tag: string;
  placeholder: string;
};

type PersonalMantaroryFields = {
  name: MandatoryFieldsContent;
};
type CompanyMantaroryFields = {
  corporateName: MandatoryFieldsContent;
  companyTaxNumber: MandatoryFieldsContent;
};

const InvoiceData: {
  [key in ApiInvoiceType]: {
    ch: string;
    defaultMandatoryData: PersonalMantaroryFields | CompanyMantaroryFields;
  };
} = {
  [ApiInvoiceType.Personal]: {
    ch: "个人",
    defaultMandatoryData: {
      name: {
        value: "",
        tag: "姓名",
        placeholder: "输入个人名称",
      },
    },
  },
  [ApiInvoiceType.Company]: {
    ch: "企业单位",
    defaultMandatoryData: {
      corporateName: {
        value: "",
        tag: "公司名称",
        placeholder: "输入公司名称",
      },
      companyTaxNumber: {
        value: "",
        tag: "公司税号",
        placeholder: "输入公司税号",
      },
    },
  },
};

enum WechatInvoiceType {
  Company = 0,
  Individual = 1,
}

const DEFAULT_INVOICE_TYPE = ApiInvoiceType.Personal;

export default function UserInvoiceSelect() {
  const { userInfoState } = useUserInfo();
  const { userData } = userInfoState;
  const { applicationState, dispatch } = useApplicationInfo();
  const { invoiceOrderNumbers: orderNos } = applicationState;

  const [updatedFromWechat, setUpdatedFromWechat] = useState(false);
  // Mandatory data
  const [invoiceType, setInvoiceType] = useState(DEFAULT_INVOICE_TYPE);
  const [email, setEmail] = useState(userData?.userInfo.email ?? "");
  // Mandatory depending on invoice-type data
  const [mandatoryFieldsData, setMandatoryFieldsData] = useState<
    PersonalMantaroryFields | CompanyMantaroryFields
  >(InvoiceData[DEFAULT_INVOICE_TYPE].defaultMandatoryData);

  useEffect(() => {
    if (updatedFromWechat) {
      // No-op, simply reset
      setUpdatedFromWechat(false);
    } else {
      // Set to default data per type
      setMandatoryFieldsData(InvoiceData[invoiceType].defaultMandatoryData);
    }
  }, [invoiceType]);

  const handleWechatFapiaInfo = (
    invoiceData: Taro.chooseInvoiceTitle.SuccessCallbackResult
  ) => {
    switch (+invoiceData.type as WechatInvoiceType) {
      case WechatInvoiceType.Company:
        if (invoiceType !== ApiInvoiceType.Company) {
          setInvoiceType(ApiInvoiceType.Company);
          setUpdatedFromWechat(true);
        }
        const defaultData = InvoiceData[ApiInvoiceType.Company]
          .defaultMandatoryData as CompanyMantaroryFields;

        setMandatoryFieldsData({
          ...defaultData,
          corporateName: {
            ...defaultData.corporateName,
            value: invoiceData.title,
          },
          companyTaxNumber: {
            ...defaultData.companyTaxNumber,
            value: invoiceData.taxNumber,
          },
        });
        break;
      case WechatInvoiceType.Individual:
        setInvoiceType(ApiInvoiceType.Personal);
        // TODO: not getting any sample data from wechat for this case
        break;

      default:
        break;
    }
  };

  // Used for very basic validation (disable)
  const mandatoryFieldsFilled = !Object.values(mandatoryFieldsData).filter(
    (value) => value.value === ""
  ).length;
  const emailFilled = !!email.length;

  return (
    <Layout>
      <UserSubPageBase
        title="申请电子发票"
        subTitleDark={`${InvoiceData[invoiceType].ch}发票`}
        scrollable
      >
        <View className={style["invoice-form-wrapper"]}>
          <View className={style.tag}>抬头类型</View>

          {/* Mandatory fields */}
          <Picker
            onChange={(event) => {
              const selected = INVOICE_TYPE_ARR[
                event.detail.value
              ] as ApiInvoiceType;
              setInvoiceType(selected);
            }}
            range={INVOICE_TYPE_ARR.map((invType) => InvoiceData[invType].ch)}
          >
            <View className={`${style.input} ${style.picker}`}>
              <View>{InvoiceData[invoiceType].ch}</View>
              <Icon type="DownChevronBlack" className={style.chevron} />
            </View>
          </Picker>

          <View className={style.tag}>电子邮件</View>
          <Input
            className={style.input}
            type="text"
            onInput={(e) => {
              console.warn("currently no email-input validation");
              setEmail(e.detail.value);
            }}
            placeholder="请输入电子邮箱"
            value={email}
          />
          {/* End mandatory fields */}

          {/* Invoice type dependent fields */}
          {Object.entries(mandatoryFieldsData).map(([key, value]) => (
            <View key={key}>
              <View className={style.tag}>{value.tag}</View>
              <Input
                className={style.input}
                type="text"
                onInput={(e) => {
                  setMandatoryFieldsData((prev) => ({
                    ...prev,
                    [key]: { ...prev[key], value: e.detail.value },
                  }));
                }}
                placeholder={value.placeholder}
                value={value.value}
              />
            </View>
          ))}
          {/* End invoice type dependent fields */}

          <View
            onClick={() => {
              Taro.chooseInvoiceTitle({
                success: handleWechatFapiaInfo,
              });
            }}
            className={style["wechat-cta"]}
          >
            <Icon className={style["wechat"]} type="WeChat" />
            <View className={style.text}>使用微信发票抬头</View>
          </View>
        </View>

        <View className={style["dock-wrapper"]}>
          <C13BottomDock
            onPrimaryClick={{
              text: "提交",
              cb: async () => {
                const payload = {
                  email,
                  orderNos,
                  type: invoiceType,
                  ...Object.entries(mandatoryFieldsData).reduce(
                    (accumObj, [key, value]) => ({
                      ...accumObj,
                      [key]: value.value,
                    }),
                    {}
                  ),
                };

                const invoiceIdorNull = await submitInvoice(payload);
                if (invoiceIdorNull !== null) {
                  dispatch({
                    type: "SHOW_MODAL",
                    data: ModalTypes.InvoiceConfirmation,
                  });
                }
              },
              disabled: !(mandatoryFieldsFilled && emailFilled),
            }}
            onSecondaryClick={{
              text: "无需发票",
              cb: () => {
                Taro.navigateBack();
              },
            }}
          />
        </View>
      </UserSubPageBase>
    </Layout>
  );
}
